<template>
  <div class="topForm upload">
    <vxe-toolbar size="mini">
      <template v-slot:buttons>
        <template v-if="!isShowDownBtn">
          <el-button size="small" type="primary" @click="openDialog()">上传</el-button>
          <el-button size="small" type="danger" @click="removeSelected()">删除</el-button>
          <el-button type="primary" @click="downLoadSelected()">批量下载</el-button>
        </template>
        <el-button v-else size="small" type="primary" @click="downLoadSelected()"
          >批量下载</el-button
        >
      </template>
    </vxe-toolbar>
    <vxe-table
      border
      show-overflow
      resizable
      ref="fileTableRef"
      class="vxe-table-element"
      size="mini"
      :align="cooperationList ? 'center' : 'left'"
      :auto-resize="true"
      :data="tableData"
      :toolbar="tableToolbar"
      @select-change="handleSelectionChange"
      @select-all="handleSelectionChange"
      @cell-dblclick="handleDblclick"
      @radio-change="handleRadioChange"
    >
      <vxe-table-column type="checkbox" width="50" fixed="left"></vxe-table-column>
      <vxe-table-column type="seq" width="60" title="序号"></vxe-table-column>
      <vxe-table-column
        v-for="(item, index) in columnList"
        :key="index"
        :fixed="item.fixed"
        :sortable="item.sortable"
        :field="item.prop"
        :title="item.label"
      >
        <template v-slot="{ row }">
          <span v-if="item.prop === 'fileType'">{{ format(row[item.prop]) }}</span>
          <span v-if="item.prop === 'operation'">
            <el-button type="text" @click="() => openViewHandler(row)">查看</el-button>
          </span>
          <span v-else>{{ row[item.prop] }}</span>
        </template>
      </vxe-table-column>
    </vxe-table>
    <ViewFile ref="viewFileRef" />
    <UploadDialog
      ref="uploadDialogRef"
      :dictType="dictType"
      @upload="uploadHandler"
      v-bind="$attrs"
    />
  </div>
</template>
<script>
  import API from '@/api/dataBase';
  import { dateTimeFormat } from '@/filters/index';
  import baseUrl from '@/common/config';
  import { formatDate } from '@/utils';
  import ViewFile from './../ViewFile';
  import UploadDialog from './../UploadDialog';
  export default {
    name: 'IEUploadFileType',
    props: {
      //默认值
      tableData: {
        type: Array,
        default: () => [],
      },

      cooperationList: {
        type: Boolean,
        default: () => false,
      },
      dbClickDownload: {
        type: Boolean,
        default: false,
      },
      isShowDownBtn: {
        type: Boolean,
        default: false,
      },
      dictType: {
        type: String,
        default: '',
      },
    },
    data() {
      let newDate = dateTimeFormat(new Date());
      return {
        dialogVisible: false,
        uploadForm: {
          fileType: null,
        },
        viewFileList: [],
        uploadDialogType: null, //当前交易类型
        multipleSelection: [], //存放选中的值
        todayDate: newDate,
        actionUrl: '',
        tableToolbar: {
          id: 'toolbar',
        },
        columnList: [
          {
            prop: 'attachmentName',
            label: '附件名称',
          },
          {
            prop: 'fileType',
            label: '附件类型',
          },
          { prop: 'createBy', label: '上传人' },
          { prop: 'gmtCreate', label: '上传日期' },
          { prop: 'operation', label: '操作' },
        ],
        fileTypeList: [],
        uploadTableData: this.tableData,
      };
    },
    mounted() {
      this.actionUrl = baseUrl + API.OSS_UPLOAD_API;
      this.fileTypeList = this.dictListMap[this.dictType] || [];
    },
    methods: {
      openViewHandler(rowItem) {
        this.$refs.viewFileRef.openViewHandler(rowItem);
      },
      //设置单选选中
      setRadioRow(val) {
        this.$refs.fileTableRef.setRadioRow(val);
        this.multipleSelection = [this.$refs.fileTableRef.getRadioRecord()];
      },
      formatDateStr(item) {
        return formatDate(item);
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },

      uploadHandler(data) {
        console.log('上传成功11', data);
        this.uploadTableData.push(data);
        this.$refs.fileTableRef.reloadData(this.uploadTableData);
        this.$emit('upload', this.uploadTableData);
      },

      //checkbox选中触发事件
      handleSelectionChange(row) {
        this.multipleSelection = row.selection;
      },
      //radio表格选中事件
      handleRadioChange(val) {
        this.multipleSelection = [val.row];
      },
      getTableData(isFormatData = true) {
        const $table = this.$refs.fileTableRef;
        if (isFormatData) {
          const tableData = this.tableData;
          return tableData.map((item) => {
            return {
              ...item,
              gmtCreate: this.formatDateStr(item.gmtCreate),
            };
          });
        } else {
          return $table.getTableData().fullData;
        }
      },
      //删除
      removeSelected() {
        let _self = this;
        if (this.multipleSelection.length === 0) {
          this.$message({
            showClose: true,
            message: this.$t('upload.noSelectDel'),
            type: 'error',
          });
        } else {
          this.$confirmAction()
            .then(() => {
              this.$refs['fileTableRef'].removeSelecteds();
              this.uploadTableData = this.tableData.filter((item) => {
                let flag = true;
                this.multipleSelection.map((select) => {
                  if (item._XID == select._XID) {
                    flag = false;
                  }
                });
                return flag;
              });
              //如果操作成功，直接返回列表
              this.$message({
                type: 'success',
                message: this.$t('message.success'),
              });
              _self.$emit('upload', this.uploadTableData);
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: this.$t('confirm.deleteCancelled'),
              });
            });
        }
      },
      downLoadSelected() {
        if (this.multipleSelection.length === 0) {
          this.$message({
            showClose: true,
            message: this.$t('upload.noSelectDownLoad'),
            type: 'error',
          });
        } else {
          let params = {
            keyList: this.multipleSelection.map((it) => it.attachmentKey),
          };
          this.$axios.post(API.DOWNLOAD_FILE, params).then((res) => {
            if (res.data.code == 0) {
              res.data.data.map((it) => {
                this.downloadFile(it);
              });
            }
          });
        }
      },
      //多个文件下载
      downloadFile(url) {
        window.open(url, '_blank');
      },
      //双击下载文档
      handleDblclick(data) {
        if (this.dbClickDownload) {
          const a = document.createElement('a');
          a.href = data.row.attachmentPath;
          a.target = '_blank';
          a.click();
        }
      },
      // uploadChange(file, fileList) {
      //   if (!this.uploadForm.fileType) {
      //     this.$message.error('请先选择文件类型');
      //     return;
      //   }
      //   const lastItem = fileList.pop();
      //   fileList.push({ ...lastItem, fileType: this.uploadForm.fileType });
      //   this.viewFileList = fileList.filter((item) => item.fileType);
      // },

      cancelSelect() {
        this.$refs.upload.clearFiles();
        this.dialogVisible = false;
      },
      confirmUpload() {
        if (this.viewFileList.length <= 0) {
          this.$message({
            showClose: true,
            message: '请选择文件',
            type: 'error',
          });
          return;
        }
        this.$refs.upload.submit();
        this.dialogVisible = false;
      },
      openDialog() {
        this.$refs.uploadDialogRef.openDialog();
      },
      format(item) {
        let fileName = '-';
        this.fileTypeList.forEach((val) => {
          if (val.value === item) {
            fileName = val.label;
          }
        });
        return fileName;
      },
    },
    components: {
      ViewFile,
      UploadDialog,
    },
    watch: {
      tableData() {
        console.log(this.tableData);
        debugger;
        this.uploadTableData = this.tableData;
      },
    },
  };
</script>

<style lang="scss" scoped>
  .uploadBtn {
    float: left;
    padding-right: 16px;
  }
  .dialog-body {
    display: flex;
    justify-content: center;
    flex-direction: column;
    ::v-deep .el-upload-list {
      display: none !important;
    }
    .function-item {
      display: flex;
      .el-form {
        padding-right: 20px;
      }
    }
    .upload-file-list-wrap {
      .file-label {
        text-align: right;
        font-size: 14px;
        margin-right: 10px;
      }
      .upload-file-list {
        padding-left: 20px;
        list-style: none;
        display: flex;
        flex-direction: row;
        a {
          padding-left: 10px;
        }
      }
    }
  }
  ::v-deep .el-dialog__footer {
    text-align: center;
  }
</style>
